// 屏幕适配 mixin 函数

// * 设计稿尺寸（px）
const baseWidth = 1920
const baseHeight = 1080

export default {
  data() {
    return {
      // * 定时函数
      drawTiming: null,
      // * 缩放比例
      scale: {
        width: 1,
        height: 1
      }
    }
  },
  mounted () {
    this.calcRate()
    window.addEventListener('resize', this.resize)
  },
  beforeDestroy () {
    window.removeEventListener('resize', this.resize)
  },
  methods: {
    calcRate () {
      const appRef = this.$refs["appRef"]
      if (!appRef) return

      // 获取内容区域的实际尺寸
      const contentArea = document.querySelector('.content-area')
      if (!contentArea) return

      const contentWidth = contentArea.clientWidth
      const contentHeight = contentArea.clientHeight

      // 计算缩放比例
      let scaleWidth = contentWidth / baseWidth
      let scaleHeight = contentHeight / baseHeight
      
      // 保持宽高比例一致，取较小的缩放比例
      const scale = Math.min(scaleWidth, scaleHeight)
      
      // 设置最小和最大缩放限制
      const minScale = 0.5
      const maxScale = 1.2
      const finalScale = Math.min(Math.max(scale, minScale), maxScale)

      // 计算居中位置
      const scaledWidth = baseWidth * finalScale
      const scaledHeight = baseHeight * finalScale
      const left = (contentWidth - scaledWidth) / 2
      const top = (contentHeight - scaledHeight) / 2

      // 应用样式
      appRef.style.width = `${baseWidth}px`
      appRef.style.height = `${baseHeight}px`
      appRef.style.position = 'absolute'
      appRef.style.transform = `scale(${finalScale})`
      appRef.style.transformOrigin = '0 0'
      appRef.style.left = `${left}px`
      appRef.style.top = `${top}px`
      
      // 更新scale对象
      this.scale.width = finalScale
      this.scale.height = finalScale
    },
    resize () {
      clearTimeout(this.drawTiming)
      this.drawTiming = setTimeout(() => {
        this.calcRate()
      }, 200)
    }
  },
}